'''
.. module:: CEmailFrame
   :platform: Unix
   :synopsis: This module defines the CEmailFrame class 

.. moduleauthor:: Daniel Chee
'''
import Tkinter

from gui.cGui.widgets.CFrame import CFrame
from gui.cGui.widgets.CListBox import CListBox
from gui.cGui.widgets.CButton import CButton
from gui.cGui.widgets.CText import CText
from gui.cGui.widgets.CEntry import CEntry
from deliveryMethod.Mailer import Mailer
from CIVEntry import CIVEntry
from CIVText import CIVText

from ReportFramework.ReportFramework import loadReports
from ReportFramework.ReportFramework import getExample

from ScanEvent.ScanEvent import fromString

from gui.cGui.widgets.CLabel import CLabel
from ScanEvent.ScanEvent import EmailItem

class CEmailFrame2(CFrame):
    '''
    A Frame that allows the user of Cernent of add/edit/remove email items from the current scan event
    '''
    
    
    '''
    *************************************** INITIALIZATION ***********************************************
    '''
    def __init__(self, master, scanEventEditor, conf):
        '''
        Creates a new CEmailFrame.
        
        Args:
        
            master: The widget this frame will be attached to. 
            
            scanEventEditor: The event editor this frame is associated with. This is needed in 
                             order to track changes for dirty detection. 
        
        '''
        CFrame.__init__(self, master)
        self.conf = conf
        self._initialize()
        
    def _initialize(self):
        self._createPanel1()
        self._createPanel2()
        self._createPanel3()
        self._initializeEmailItems()
        
    def _createPanel1(self):
        self._createCLabel("Email Items", 0, 0)
        fs = [("<ButtonRelease-1>", self._getSelection)]
        self.listbox = self._createListbox(1, 0, rowSpan = 5, xPad = 5, yPad = 5, funcs = fs)
        self._createButtonFrame(6, 0, buttons = ["Add", "Remove"], cmd = [self._addEmailItem, self._removeEmailItem])
        self._createButtonFrame(8, 0, buttons = ["Test Email Item"], cmd = [self._testEmailItem])
        
    def _createPanel2(self):
        self._createCLabel("EDIT EMAIL ITEM", 0, 1)
        fs = [("<FocusOut>", self._isEmailValid)]
        self.name = self._createEntry(1, 1, funcs = fs)
        self.emails = self._createEntry(2, 1, funcs = fs)
        self.subject = self._createEntry(3, 1,funcs = fs)
        self.text = self._createTextbox(4, 1, rowSpan = 8, funcs = fs)
        
    def _createPanel3(self):
        self._createCLabel("Available Reports", 0, 2)
        fs = [("<ButtonRelease-1>", self._getSelection)]
        self.availableReports = self._createListbox(1, 2, rowSpan = 4, funcs = fs, mode = 'extended')
        for key in loadReports().keys():
            self.availableReports.insert(Tkinter.END, key)
        self._createButtonFrame(5, 2, buttons = ["Include", "Preview"], cmd = [self._includeReports(), self._previewReport()])
        self._createCLabel("Included Reports", 6, 2)
        fs = [("<ButtonRelease-1>", self._getSelection)]
        self.includedReports = self._createListbox(7, 2, rowSpan = 3, funcs = fs)
        self._createButtonFrame(10, 2, buttons = ["Remove"], cmd = [self._removeReports])
    
    def _initializeEmailItems(self):
        self.emailItems = []
        self.setEmailItems(self.emailItems)
    
    
    '''
    *************************************** COMPONENT CREATOR METHODS ***********************************************
    '''
    
    def _createCLabel(self, inText, r, c, xPad = 5, yPad = 5):
        newLabel = CLabel(master = self, text = inText)
        newLabel.grid(row=r, column=c, sticky = "NEW", pady=yPad, padx=xPad)
        return newLabel
    
    def _createEntry(self, r, c, xPad = 5, yPad = 5, funcs = []):
        entryVar = Tkinter.StringVar()
        entry = CEntry(master = self, textvariable = entryVar)
        entry.grid(row=r, column=c, sticky = "NEWS", pady=yPad, padx=xPad)
        if funcs:
            for func in funcs:
                entry.bind(func[0], func[1])
        return entryVar
        
    def _createTextbox(self, r, c, rowSpan, xPad = 5, yPad = 5, funcs = []):
        textbox = CText(master = self)
        textbox.grid(row = r, column = c, rowspan = rowSpan, sticky = "NEWS", pady=yPad, padx=xPad)
        if funcs:
            for func in funcs:
                textbox.bind(func[0], func[1])
        return textbox
    
    def _createListbox(self, r, c, rowSpan = 1, xPad = 5, yPad = 5, funcs = [], mode = 'normal'):
        listbox = CListBox(master = self)
        listbox.grid(row = r, column = c, rowspan = rowSpan, sticky = "NEWS", pady=yPad, padx=xPad)
        listbox.config(selectmode = mode)
        if funcs:
            for func in funcs:
                listbox.bind(func[0], func[1])
        return listbox
    
    def _createButtonFrame(self, r, c, rowSpan = 1, xPad = 5, yPad = 5, buttons = [], cmd = []):
        buttonFrame = CFrame(master = self)
        for i in range(len(buttons)):
            newButton = CButton(master = buttonFrame, text = buttons[i], command = cmd[i])
            newButton.grid(row = 0, column = i, sticky = "NEWS", pady=yPad, padx=xPad)
        buttonFrame.grid(row = r, column = c, rowspan = rowSpan, sticky = "NEWS", pady=yPad, padx=xPad)
    
    '''
    *************************************** ACTION METHODS ***********************************************
    '''
    
    def _getSelection(self, event):
        self._saveItem()
        self.currentSelection = int(self.listbox.curselection()[0])
        self._updateGUI()
        #self._updateGUI()
        #if self.currentSelection >= 0:
        #    self.emailItemList[self.currentSelection] = self.displayFrame.getItem()
        #self.currentSelection = int(self.listbox[0].curselection()[0])
        #newItem = self.emailItemList[int(self.listbox[0].curselection()[0])]
        #self.displayFrame.setItem(newItem)
    
    def _addEmailItem(self):
        self.emailItems.append(['Admin', self.conf['administrators'], self.conf['subject'], self.conf['message'], []]);
        self.listbox.delete(0, Tkinter.END)
        index = 0
        for item in self.emailItems:
            self.listbox.insert(index, item[0])
            index = index + 1
        self._updateGUI()
        #self.currentSelection = len(self.emailItemList)
        #self.listbox[0].insert(Tkinter.END, '< New Item >')
        #self.emailItemList.append(['', '', '', '', []])
        #self.displayFrame.setItem(self.emailItemList[self.currentSelection])
        
    def _removeEmailItem(self):
        self.listbox.delete(0, Tkinter.END)
        index = 0
        for item in self.emailItems:
            self.listbox.insert(index, item[0])
            index = index + 1
        pass
        #for selection in self.listbox[0].curselection():
        #    self.listbox[0].delete(selection)
        #    self.emailItemList.pop(int(selection))
        #self.displayFrame.clearEntries()
    
    def _isEmailValid(self, event):
        pass
        #for addr in self.emails[1].get().split(","):
        #    if not re.match(r"[^@]+@[^@]+\.[^@]+", addr):
        #        print "The email is not valid"
        
    def _testEmailItem(self):
        pass
        
    def _includeReports(self):
        pass
    
    def _previewReport(self):
        pass
        
    def _removeReports(self):
        pass
        
    '''
    *************************************** OTHER METHODS ***********************************************
    '''
    
    def setEmailItems(self, emailItems):
        self.emailItems = emailItems
        if not emailItems:
            self.currentSelection = 0
            self._addEmailItem()
        else:
            self._updateGUI()
            
    def _saveItem(self):
        item = self.emailItems[self.currentSelection]
        item[0] = self.name.get()
        item[1] = self.emails.get()
        item[2] = self.subject.get()
        item[3] = self.text.get("1.0", Tkinter.END)
        item[4] = self.includedReports.get(0, Tkinter.END)
            
    def _updateGUI(self):
        item = self.emailItems[self.currentSelection]
        self.name.set(item[0])
        self.emails.set(item[1])
        self.subject.set(item[2])  
        self.text.delete('1.0', Tkinter.END)
        self.text.insert("1.0", item[3])
        self.includedReports.delete(0, Tkinter.END)
        for report in item[4]:
            self.includedReports.insert(Tkinter.END, report)
        
if __name__ == "__main__":
    test = Tkinter.Tk()
    test.title("Test")
    frame = CEmailFrame2(test, None, {'mailer': Mailer('cernentteam@gmail.com', 'cernentteam@gmail.com', 'smtp.gmail.com', '587', smtpUser='cernentteam', smtpPass='Coffee.Eat.Rope'), 'examplePath': '/opt/cernent/resources/example.nessus', 'archivePath': '/opt/cernent/archive/', 'administrators': 'dchee7@unm.edu', 'reportPath': '/opt/cernent/reports/', 'message': 'Hello,\n\nAttached are the vulnerability reports requested.\n\nRegards,\nIT Security Department\n', 'scanners': {'Main Scanner': ['127.0.0.1', 8834, 'bob', 'bob']}, 'subject': '-= Vulnerability Report =-'})
    #frame.setEmailItems(fromString("['admin', 'admin1@foo.com, admin2@bar.com', 'reports', u'Here are the reports.\\n', ['Concise', 'JavaJRE']]^['exec', 'exec1@foo.com, exec2@bar.com', 'report', u'Here is the report\\n', ['Credentialed']]\n"))
    #frame = CEmailFrame2(test, None, None)
    frame.grid(row = 0, column = 0, sticky = "NEWS")
    test.mainloop()
        
        
        
        
        
        
        